<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="900"
    :before-close="handleClose"
  >
    <div class="dialogMain">
      <el-descriptions title="报名课程" border :column="1">
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">课程名称</div>
          </template>
          {{ params?.curriculum_Info?.name }}
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">课程内容</div>
          </template>
          <div>
            <div
              class="lessonBox"
              v-for="(item, index) in info.selectLesson"
              :key="index"
            >
              {{ index + 1 }}.{{ item.name }}
            </div>
          </div>
        </el-descriptions-item>

        <!-- 折扣价 -->
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">课程价格</div>
          </template>
          <span v-if="isEdit">
            <el-input v-model="params.price" placeholder="请输入价格">
              <template #prepend>¥</template>
            </el-input>
          </span>
          <span v-else>¥{{ proxy.$utils.formatNumber(params.price) }}</span>
        </el-descriptions-item>

        <!-- 订单金额 -->
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">订单金额</div>
          </template>
          ¥{{ proxy.$utils.formatNumber(params.displayPrice) || 0 }}
        </el-descriptions-item>

        <!-- 修改预付款 -->
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="isEdit && params.hasOwnProperty('signUpPrice')"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">预付款价格</div>
          </template>
          <span>
            <el-input v-model="params.signUpPrice" placeholder="请输入价格">
              <template #prepend>¥</template>
            </el-input>
          </span>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="报名资料" border :column="1">
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          :label="label_format(item.label)"
          v-for="(item, index) in descriptions"
          :key="index"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">
              {{ label_format(item.label) }}
            </div>
          </template>
          <div v-if="item.label == 'affiliation'">
            {{ item.value.toString() }}
          </div>
          <div v-else-if="['enterprise', 'enterpriseTax'].includes(item.label)">
            {{ counter.showEnterprise(info.model, item.label) }}
          </div>
          <div
            v-else-if="
              ['certificate_scancopy', 'identification_scancopy'].includes(
                item.label
              )
            "
          >
            <div v-if="item.value">
              <div v-if="proxy.$utils.isString(item.value)">
                <div v-for="(el, idx) in item.value.split(',')" :key="idx">
                  <!-- <el-link type="primary" :href="el" target="_blank">{{el}}</el-link> -->
                  <img :src="el" alt="" v-if="isImageUrl(el)" />
                  <el-link type="primary" :href="el" target="_blank" v-else>{{
                    el
                  }}</el-link>
                </div>
              </div>
              <div v-else-if="proxy.$utils.isArrayOrJsonArray(item.value)">
                <div v-for="(el, idx) in item.value" :key="idx">
                  <el-image
                    :preview-src-list="previewList(item.value)"
                    style="width: 100px; height: 100px; margin-top: 10px"
                    :src="el.path ? el.path : el"
                    v-if="isImageUrl(el)"
                  />
                  <el-link
                    type="primary"
                    v-else
                    :href="el.path"
                    target="_blank"
                    >{{ fileName(item.label, model.name, idx) }}</el-link
                  >
                </div>
              </div>
            </div>
          </div>
          <div v-else>{{ item.value }}</div>
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          :label="item.title"
          v-for="(item, index) in info.relationList"
          :key="index"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">
              {{ item.title }}
            </div>
          </template>
          <div v-if="item.type == 'image'">
            <img :src="item.value" alt="" />
          </div>
          <div v-else-if="['templateFile', 'file'].includes(item.type)">
            <div v-if="proxy.$utils.isString(item.value)">
              <div v-for="(el, idx) in item.value.split(',')" :key="idx">
                <el-image
                  :preview-src-list="previewList(item.value.split(','))"
                  style="width: 100px; height: 100px; margin-top: 10px"
                  :src="el.path ? el.path : el"
                  v-if="isImageUrl(el)"
                />
                <el-link type="primary" v-else :href="el" target="_blank">{{
                  fileName(item.title, model.name, idx)
                }}</el-link>
              </div>
            </div>
            <div v-else-if="proxy.$utils.isArrayOrJsonArray(item.value)">
              <div v-for="(el, idx) in item.value" :key="idx">
                <el-image
                  :preview-src-list="previewList(item.value)"
                  :initial-index="0"
                  style="width: 100px; height: 100px; margin-top: 10px"
                  :src="el.path ? el.path : el"
                  v-if="isImageUrl(el)"
                />
                <el-link
                  type="primary"
                  v-else
                  :href="el.path ? el.path : el"
                  target="_blank"
                  >{{ fileName(item.title, model.name, idx) }}</el-link
                >
              </div>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="付款记录" border :column="1">
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.pay_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">
              {{ params.signUpPrice ? "预付款" : "支付金额" }}
            </div>
          </template>
          <el-text class="mx-1" type="success">{{
            proxy.$utils.formatNumber(params.pay_info.pay_amount.total / 100)
          }}</el-text>
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.pay_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">
              {{ params.signUpPrice ? "预付款时间" : "支付时间" }}
            </div>
          </template>
          {{ proxy.$utils.dateTimeFormateFn(params.pay_info.pay_time, "all") }}
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.pay_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">
              {{ params.signUpPrice ? "预付款单号" : "支付单号" }}
            </div>
          </template>
          {{ params.pay_info.transaction_id }}
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.signUpPrice"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款应付金额</div>
          </template>
          {{
            proxy.$utils.formatNumber(
              Number(params.price) - Number(params.signUpPrice)
            )
          }}
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.signUpPrice"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款实付金额</div>
          </template>
          <el-text class="mx-1" type="success" v-if="params.balance_pay_info">{{
            proxy.$utils.formatNumber(
              params.balance_pay_info.pay_amount.total / 100
            )
          }}</el-text>
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.signUpPrice"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款支付时间</div>
          </template>
          <div v-if="params.balance_pay_info">
            {{
              proxy.$utils.dateTimeFormateFn(
                params.balance_pay_info.pay_time,
                "all"
              )
            }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.signUpPrice"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款支付单号</div>
          </template>
          <div v-if="params.balance_pay_info">
            {{ params.balance_pay_info.transaction_id }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">支付总计</div>
          </template>
          <el-text class="mx-1">{{
            proxy.$utils.formatNumber(params.payPrice) || 0
          }}</el-text>
        </el-descriptions-item>

        <!-- 优惠减免 -->
        <div v-for="(item, index) in discounts" :key="index">
          <el-descriptions-item label-class-name="descriptionsLabel150">
            <template #label>
              <div class="cell-item descriptionsLabel150">
                优惠减免金额（{{ index + 1 }}）
              </div>
            </template>
            <div style="color: #f56c6c" class="bold">
              {{ proxy.$utils.formatNumber(item.discountPrice) }}
            </div>
            <!-- <el-text class="mx-1 errColor" type="danger"></el-text> -->
          </el-descriptions-item>
          <el-descriptions-item label-class-name="descriptionsLabel150">
            <template #label>
              <div class="cell-item descriptionsLabel150">
                优惠减免时间（{{ index + 1 }}）
              </div>
            </template>
            {{ proxy.$utils.dateTimeFormateFn(item._add_time, "all") }}
          </el-descriptions-item>
          <el-descriptions-item
            label-class-name="descriptionsLabel150"
            v-if="item.differTagList && item.differTagList.length"
          >
            <template #label>
              <div class="cell-item descriptionsLabel150">
                优惠减免标签（{{ index + 1 }}）
              </div>
            </template>
            {{ differTagList_format(item.differTagList) }}
          </el-descriptions-item>
          <el-descriptions-item
            label-class-name="descriptionsLabel150"
            v-if="item.discountList.length"
          >
            <template #label>
              <div class="cell-item descriptionsLabel150">
                优惠减免单号（{{ index + 1 }}）
              </div>
            </template>
            {{ discountList_format(item.discountList, "refund_id") }}
          </el-descriptions-item>
          <el-descriptions-item
            label-class-name="descriptionsLabel150"
            v-if="item.discountList.length"
          >
            <template #label>
              <div class="cell-item descriptionsLabel150">
                优惠减免原因（{{ index + 1 }}）
              </div>
            </template>
            {{ discountList_format(item.discountList, "discountReason") }}
          </el-descriptions-item>
        </div>

        <!-- 订单金额 -->
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">订单金额</div>
          </template>
          <el-text class="mx-1" type="primary">{{
            proxy.$utils.formatNumber(params.displayPrice) || 0
          }}</el-text>
        </el-descriptions-item>

        <!-- 退款 -->
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.refund_info"
        >
          <template #label>
            <div
              class="cell-item descriptionsLabel150"
              v-if="params.balance_pay_info"
            >
              预付款退款
            </div>
            <div class="cell-item descriptionsLabel150" v-else>退款金额</div>
          </template>
          <el-text class="mx-1 errColor" type="danger">{{
            proxy.$utils.formatNumber(
              params.refund_info.refund_amount.refund / 100
            )
          }}</el-text>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.refund_info"
        >
          <template #label>
            <div
              class="cell-item descriptionsLabel150"
              v-if="params.balance_pay_info"
            >
              预付款退款时间
            </div>
            <div class="cell-item descriptionsLabel150" v-else>退款时间</div>
          </template>
          {{
            proxy.$utils.dateTimeFormateFn(
              params.refund_info.refund_time,
              "all"
            )
          }}
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.refund_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">退款单号</div>
          </template>
          {{ params.refund_info.refund_id }}
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.refund_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">退款原因</div>
          </template>
          {{ params.refund_info.refundReason }}
        </el-descriptions-item>
        <!-- 尾款退款 -->
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.balance_refund_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款金额</div>
          </template>
          <el-text class="mx-1 errColor" type="danger">{{
            proxy.$utils.formatNumber(
              params.balance_refund_info.refund_amount.refund / 100
            )
          }}</el-text>
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.balance_refund_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款时间</div>
          </template>
          {{
            proxy.$utils.dateTimeFormateFn(
              params.balance_refund_info.refund_time,
              "all"
            )
          }}
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.balance_refund_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款单号</div>
          </template>
          {{ params.balance_refund_info.refund_id }}
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="descriptionsLabel150"
          v-if="params.balance_refund_info"
        >
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款原因</div>
          </template>
          {{ params.balance_refund_info.refundReason }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <template #footer v-if="isEdit">
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
import { ref } from "vue";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();
const emit = defineEmits(["fatherMethod"]);

let dialogVisible = ref(false);
let info = ref({});
let model = ref({});
let descriptions = ref([]);
let dicts = ref([]); //字典数据
let params = ref({});
let dialogTitle = ref("");
let isEdit = ref(false); //是否编辑
let loading = ref(false);
let type = ref(""); //打开详情框主要类型
let curriculumInfo = ref({}); //课程详情
let discounts = ref([]); //优惠信息记录

function fileName(fieldNamea, name, idx) {
  let modelArr = [
    {
      name: "身份证",
      value: "identification_scancopy",
    },
    {
      name: "毕业证书",
      value: "certificate_scancopy",
    },
  ];
  for (let index = 0; index < modelArr.length; index++) {
    const element = modelArr[index];
    if (element.value == fieldNamea) return `${name}_${element.name}${idx + 1}`;
  }
  return `${name}_${getFileName(fieldNamea)}${idx + 1}`;

  function getFileName(str) {
    let a = getBracketContents(str);
    if (a.length) return a[0];
    return str;
  }
  //获取书名号里面的值
  function getBracketContents(str) {
    // 正则表达式匹配书名号内的内容
    const regex = /《([^>]+)》/g;
    let match;
    let results = [];

    // 循环查找所有匹配项
    while ((match = regex.exec(str)) !== null) {
      results.push(match[1]); // 添加书名号内的内容到结果数组
    }

    return results; // 返回包含所有内容的数组
  }
}

function isImageUrl(el) {
  let a = el.path ? el.path : el;
  if (a.includes(".jpg") || a.includes(".png") || a.includes(".jpeg"))
    return true;
  return false;
}

function previewList(array) {
  let arr = [];
  array.forEach((element) => {
    let a = element.path ? element.path : element;
    if (isImageUrl(a)) arr.push(a);
  });
  return arr;
}

async function open(e, canEdit?) {
  // model.value = proxy.$utils.deepcopy(row).approvalContent.model;
  let row = await proxy.$apis.orderAction({
    type: "details",
    data: { _id: e._id },
  });
  info.value = proxy.$utils.deepcopy(row).approvalContent;
  row.curriculum_Info = e.curriculum_Info;
  params.value = proxy.$utils.deepcopy(row);
  getDiscountInfo();
  curriculumDetails();
  console.log("订单详情", params.value);
  dialogTitle.value = `${canEdit && canEdit == 1 ? "修改订单" : "报名详情"} - ${
    row.approvalContent.model.name
  } - ${row.approvalContent.model.identityCard}`;
  getDict();

  if (canEdit && canEdit == 1) isEdit.value = canEdit;
  if (row.discountPrice) getWepayOrder();
  dialogVisible.value = true;
}

async function getWepayOrder() {
  let resp = await proxy.$apis.queryWepayOrder({
    payType: params.value["payType"],
    out_trade_no: params.value["out_trade_no"],
  });
  console.log("查询订单", resp);
}

function discountList_format(array, key) {
  let arr = [];
  array.forEach((element) => {
    arr.push(element.info[key]);
  });
  return proxy.$utils.unique(arr).toString();
}

//获取优惠信息
async function getDiscountInfo() {
  let resp = await proxy.$apis.orderDiscountRecord({
    type: "query",
    data: { _id: params.value["_id"] },
  });
  let pay_discount_info = params.value["pay_discount_info"] || [];
  //如果能查到说明是新版
  if (resp.length) {
    resp.forEach((element) => {
      let arr = [];
      let index = proxy.$utils.findIndexByField(
        pay_discount_info,
        "discountUid",
        element.discountUid
      );
      if (index != -1) arr.push(pay_discount_info[index]);
      element.discountList = proxy.$utils.deepcopy(arr);
    });
    let list = proxy.$utils.deepcopy(resp);
    discounts.value = list.sort(proxy.$utils.compare("_add_time"));
  } else if (pay_discount_info.length) {
    let arr = [];
    pay_discount_info.forEach((element) => {
      if (arr.length) {
        let current = proxy.$utils.findIndexByField(
          arr,
          "discountReason",
          element.info.discountReason
        );
        if (current != -1) {
          let _add_time_str = proxy.$utils.dateTimeFormateFn(
            element.info.create_time,
            "all"
          );
          let _add_time = proxy.$utils.getTimeFn(_add_time_str);
          const difference = Math.abs(_add_time - arr[current]._add_time);
          if (difference <= 5000) {
            arr[current].discountList.push(element);
            arr[current].discountPrice += element.info.amount.refund / 100;
          } else {
            arr.push({
              discountList: [element],
              discountPrice: element.info.amount.refund / 100,
              discountReason: element.info.discountReason,
              _add_time,
            });
          }
        }
      } else {
        let _add_time = proxy.$utils.dateTimeFormateFn(
          element.info.create_time,
          "all"
        );
        arr.push({
          discountList: [element],
          discountPrice: element.info.amount.refund / 100,
          discountReason: element.info.discountReason,
          _add_time: proxy.$utils.getTimeFn(_add_time),
        });
      }
    });
    discounts.value = arr;
  }
}

//课程详情
async function curriculumDetails() {
  curriculumInfo.value = await proxy.$apis.course({
    type: "details",
    data: { _id: params.value["curriculum_id"] },
  });
  //console.log("课程详情", curriculumInfo.value);
  getModel();
  getDescriptions();
}

function getDescriptions() {
  let list = proxy.$utils.objTurnArr(model.value);
  descriptions.value = moveObjectAfter(
    list,
    "enterpriseJurisdiction",
    "enterpriseTax"
  );
}

function getModel() {
  //console.log("needUserParams", curriculumInfo.value.needUserParams);
  if (
    curriculumInfo.value["needUserParams"] &&
    curriculumInfo.value["needUserParams"].length
  ) {
    let obj = {};
    curriculumInfo.value["needUserParams"].forEach((element) => {
      obj[element.fieldName] = "";
    });
    model.value = proxy.$utils.formatFunction(info.value["model"], obj);
  }
}

//更换json数组位置
function moveObjectAfter(jsonArray, value1, value2) {
  const indexOfValue1 = jsonArray.findIndex((item) => item.label === value1);
  const indexOfValue2 = jsonArray.findIndex((item) => item.label === value2);
  if (indexOfValue1 === -1 || indexOfValue2 === -1) {
    return jsonArray; // 如果要查找的值对应的对象不存在，直接返回原数组
  }
  const elementToMove = jsonArray.splice(indexOfValue1, 1)[0];
  const insertIndex = indexOfValue2;
  jsonArray.splice(insertIndex, 0, elementToMove);
  return jsonArray;
}

function differTagList_format(e) {
  let arr = [];
  e.forEach((element) => {
    arr.push(element.tagname);
  });
  return arr.toString();
}

async function save() {
  try {
    loading.value = true;
    let data = { price: params.value["price"], orderId: params.value["_id"] };
    if (params.value["signUpPrice"])
      data["signUpPrice"] = params.value["signUpPrice"];
    await proxy.$apis.orderAction({
      type: "update", //修改订单金额
      data,
    });
    proxy.$utils.showToast("修改成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function label_format(e) {
  if (!dicts.value.length) return;
  let index = proxy.$utils.findIndexByField(dicts.value, "dict_code", e);
  if (index != -1) return dicts.value[index].dict_label;
}

async function getDict() {
  let { data } = await proxy.$apis.dict({
    type: "details",
    data: {
      code: "user_info",
    },
  });
  dicts.value = data;
}

function handleClose() {
  info.value = {};
  model.value = {};
  descriptions.value = [];
  dicts.value = [];
  params.value = {};
  discounts.value = [];
  dialogVisible.value = false;
}

defineExpose({ open });
</script>

<style lang="scss" scoped>
.lessonBox {
  border-bottom: 1px solid #ebeef5;
  padding: 7px 0;
}
.lessonBox:last-child {
  border-bottom: none;
}
.mx-1 {
  font-weight: bold;
}
.dialogMain {
  max-height: 65vh;
  overflow-y: auto;
}
.el-descriptions {
  margin-bottom: 20px;
  img {
    width: 100%;
    display: block;
  }
}
</style>
